package com.huaqin.customer.expansion;

import java.util.Locale;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Handler;
import android.os.SystemClock;
import android.util.Log;

import com.huaqin.customer.ConditionInterface;
import com.huaqin.salestracker.SalesTrackerService;

public class ConditionConnectTime implements ConditionInterface{

    private String mKey;
    private String mOperator;
    
    private static final int NONE = -1;
    private static final int WIFI = 1;
    private static final int CMWAP = 2;
    private static final int CMNET = 3;

    private static final String KEY_CONNECT_TIME = "NetworkConnectTime";
    private long mValues = 0;
    private long mLinkTime = 0;
    private long mConnectTime = 0;
    private boolean mExecute = false;
    private boolean mStartTime = false;
    private Handler mHandler = null;
    private Runnable mThread = null;
    
    @Override
    public void setParam(String key, String operator, String values) {
        // TODO Auto-generated method stub
        mKey = key;
        mOperator = operator;
        mValues = Integer.parseInt(values) *  60 * 1000;
    }

    @Override
    public boolean execute() {
        // TODO Auto-generated method stub
        Log.i("ConditionConnectTime", "==> execute()");
        
        if(!mExecute){
            
            if(mHandler == null){
                mHandler = new Handler();
            }
            
            if(mThread == null){
                mThread = new Runnable(){

                    @Override
                    public void run() {
                        // TODO Auto-generated method stub
                        if(getResult()){
                            mHandler.removeCallbacks(mThread);
                            sendBrocast();
                        }
                        else{
                            mHandler.postDelayed(mThread, 60 * 1000);
                        }
                    }
                    
                };
            }

            if(mKey.equals(KEY_CONNECT_TIME)){
                mHandler.postDelayed(mThread, 100);
            }
            
            mExecute = true;
        }
        
        return false;
    }

    @Override
    public void finish() {
        // TODO Auto-generated method stub
        if(mThread != null){
            mHandler.removeCallbacks(mThread);
        }
    }

    @Override
    public boolean getResult() {
        // TODO Auto-generated method stub
        boolean result = false;

        if(getAPNType(SalesTrackerService.mContext) != NONE){
            if(mLinkTime == 0){
                mLinkTime = System.currentTimeMillis();
                mStartTime = true;
            }
        }
        else{
            mLinkTime = 0;
            mStartTime = false;
        }
        
        mConnectTime = System.currentTimeMillis() - mLinkTime;
        if(mStartTime){
           if(mOperator.equals(">")){
            result = (mConnectTime > mValues);
            }
            else if(mOperator.equals(">=")){
                result = (mConnectTime >= mValues);
            }
            else if(mOperator.equals("==")){
                result = (mConnectTime == mValues);
            }
            else if(mOperator.equals("<=")){
                result = (mConnectTime <= mValues);
            }
            else if(mOperator.equals("<")){
                result = (mConnectTime < mValues);
            }
            else{
                Log.e("ConditionConnectTime", "Unknown Operator:[" + mOperator + "]");
            } 
        }
        
        if(result && mThread != null){
            mHandler.removeCallbacks(mThread);
        }

        return result;
    }

    @Override
    public String getKeyDescription() {
        // TODO Auto-generated method stub
        int totalSecond = (int)(System.currentTimeMillis() - mLinkTime)/1000;
        int hour = totalSecond / 3600;
        int minute = (totalSecond / 60) % 60;   
        int second = totalSecond % 60;
        String timeString = String.format(Locale.getDefault(), "%02d:%02d:%02d", hour, minute, second);

        return "Network Connect Time " + mOperator + " " + mValues + " Current Standby Time:" + timeString;
    }
    
    private void sendBrocast(){
        Log.i("ConditionConnectTime", "==> sendBrocast()");
        SalesTrackerService.mContext.sendBroadcast(new Intent(SalesTrackerService.STCMD_SEND_AREADY));
    }
    
    @SuppressLint("DefaultLocale")
	private int getAPNType(Context context){
        int netType = NONE; 
        
        ConnectivityManager connMgr = (ConnectivityManager)context.getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo networkInfo = connMgr.getActiveNetworkInfo();
                
        if(networkInfo != null){
            int nType = networkInfo.getType();
            
            if (nType == ConnectivityManager.TYPE_MOBILE){
                if(networkInfo.getExtraInfo().toLowerCase().equals("cmnet")){
                    netType = CMNET;
                }
                else{
                    netType = CMWAP;
                }
            }
            else if(nType == ConnectivityManager.TYPE_WIFI){
                netType = WIFI;
            }
        }
        
        Log.i("ConditionConnectTime", "netType = " + netType + "[wifi 1, wap 2; net 3]");
        return netType;
    }


}
